// Shared label templates UI logic for label template list page
// Note: This file consolidates the inline JS that was previously in
// assets/templates/assets/label_template_list.html

(function () {
  function ready(fn) {
    if (document.readyState !== 'loading') fn();
    else document.addEventListener('DOMContentLoaded', fn);
  }

  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === name + '=') {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

  function showAlert(type, message) {
    const alertHtml = `
      <div class="alert alert-${type} alert-dismissible fade show" role="alert">
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    `;
    const container = document.querySelector('.container-fluid') || document.body;
    const alertDiv = document.createElement('div');
    alertDiv.innerHTML = alertHtml;
    const el = alertDiv.firstElementChild;
    container.insertBefore(el, container.firstElementChild);
    setTimeout(() => {
      if (el && el.parentNode) el.remove();
    }, 3000);
  }

  function updatePreviewVisibility(checkboxPrefix, previewPrefix) {
    const includeQr = document.getElementById(`${checkboxPrefix}-include-qr`);
    const includeCategory = document.getElementById(`${checkboxPrefix}-include-category`);
    const includeDepartment = document.getElementById(`${checkboxPrefix}-include-department`);
    const includeUser = document.getElementById(`${checkboxPrefix}-include-user`);

    if (includeQr) {
      const target = document.getElementById(`${previewPrefix}-qr`);
      if (target) target.style.display = includeQr.checked ? 'block' : 'none';
    }
    if (includeCategory) {
      const target = document.getElementById(`${previewPrefix}-category`);
      if (target) target.style.display = includeCategory.checked ? 'block' : 'none';
    }
    if (includeDepartment) {
      const target = document.getElementById(`${previewPrefix}-department`);
      if (target) target.style.display = includeDepartment.checked ? 'block' : 'none';
    }
    if (includeUser) {
      const target = document.getElementById(`${previewPrefix}-user`);
      if (target) target.style.display = includeUser.checked ? 'block' : 'none';
    }
  }

  function bindPreviewCheckboxes(checkboxPrefix, previewPrefix) {
    ['include-qr', 'include-category', 'include-department', 'include-user']
      .map((k) => `${checkboxPrefix}-${k}`)
      .forEach((id) => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('change', () => updatePreviewVisibility(checkboxPrefix, previewPrefix));
      });
  }

  function duplicateTemplate(templateId) {
    fetch(`/assets/label-templates/${templateId}/duplicate/`, {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.success) {
          showAlert('success', data.message || '模板复制成功');
          setTimeout(() => location.reload(), 1000);
        } else {
          showAlert('danger', data.message || '复制失败');
        }
      })
      .catch(() => showAlert('danger', '网络错误，请重试'));
  }

  ready(function () {
    let selectedTemplateId = null;

    // Use template buttons
    document.querySelectorAll('.use-template-btn').forEach((btn) => {
      btn.addEventListener('click', function () {
        selectedTemplateId = this.dataset.templateId;
        const templateName = this.dataset.templateName;
        const title = document.querySelector('#useTemplateModal .modal-title');
        if (title) title.textContent = `使用模板: ${templateName}`;
      });
    });

    // Edit template buttons -> open modal and populate
    document.querySelectorAll('.edit-template-btn').forEach((btn) => {
      btn.addEventListener('click', function () {
        const data = {
          id: this.dataset.templateId,
          name: this.dataset.templateName,
          description: this.dataset.templateDescription || '',
          label_size: this.dataset.templateSize || '24mm',
          labels_per_page: this.dataset.templateLayout || '12',
          include_qr: this.dataset.templateQr === 'true',
          include_category: this.dataset.templateCategory === 'true',
          include_department: this.dataset.templateDepartment === 'true',
          include_user: this.dataset.templateUser === 'true',
          is_public: this.dataset.templatePublic === 'true',
          is_default: this.dataset.templateDefault === 'true',
        };

        // populate
        const idEl = document.getElementById('edit-template-id');
        if (!idEl) return;
        idEl.value = data.id;
        document.getElementById('edit-template-name').value = data.name;
        document.getElementById('edit-template-description').value = data.description;
        document.getElementById('edit-label-size').value = data.label_size;
        document.getElementById('edit-labels-per-page').value = data.labels_per_page;
        document.getElementById('edit-include-qr').checked = data.include_qr;
        document.getElementById('edit-include-category').checked = data.include_category;
        document.getElementById('edit-include-department').checked = data.include_department;
        document.getElementById('edit-include-user').checked = data.include_user;
        document.getElementById('edit-is-public').checked = data.is_public;
        document.getElementById('edit-is-default').checked = data.is_default;
        // For edit modal, checkboxes use 'edit-*' and preview blocks use 'preview-*'
        updatePreviewVisibility('edit', 'preview');

        const editModalEl = document.getElementById('editTemplateModal');
        if (editModalEl && window.bootstrap) {
          const editModal = new window.bootstrap.Modal(editModalEl);
          editModal.show();
        }
      });
    });

    // Bind preview checkbox changes
    bindPreviewCheckboxes('edit', 'preview');
    bindPreviewCheckboxes('create', 'create');

    // Save template changes
    const saveBtn = document.getElementById('save-template-btn');
    if (saveBtn) {
      saveBtn.addEventListener('click', function () {
        const form = document.getElementById('edit-template-form');
        if (!form) return;
        const formData = new FormData(form);
        const templateId = document.getElementById('edit-template-id').value;
        const templateName = document.getElementById('edit-template-name').value.trim();
        if (!templateName) {
          alert('请输入模板名称');
          return;
        }

        const originalText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>保存中...';
        saveBtn.disabled = true;

        fetch('/assets/label-templates/save/', {
          method: 'POST',
          body: JSON.stringify({
            template_id: templateId,
            name: formData.get('name'),
            description: formData.get('description'),
            label_size: formData.get('label_size'),
            labels_per_page: parseInt(formData.get('labels_per_page')),
            include_qr: formData.has('include_qr'),
            include_category: formData.has('include_category'),
            include_department: formData.has('include_department'),
            include_user: formData.has('include_user'),
            is_public: formData.has('is_public'),
            is_default: formData.has('is_default'),
          }),
          headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || getCookie('csrftoken'),
            'X-Requested-With': 'XMLHttpRequest',
          },
        })
          .then((r) => r.json())
          .then((data) => {
            if (data.success) {
              if (window.bootstrap) {
                const modal = window.bootstrap.Modal.getInstance(
                  document.getElementById('editTemplateModal')
                );
                if (modal) modal.hide();
              }
              showAlert('success', '模板更新成功！');
              setTimeout(() => location.reload(), 1000);
            } else {
              showAlert('danger', data.message || '更新失败，请重试');
            }
          })
          .catch(() => showAlert('danger', '网络错误，请重试'))
          .finally(() => {
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;
          });
      });
    }

    // Create template
    const createBtn = document.getElementById('create-template-btn');
    if (createBtn) {
      createBtn.addEventListener('click', function () {
        const form = document.getElementById('create-template-form');
        if (!form) return;
        const formData = new FormData(form);
        const templateName = document.getElementById('create-template-name').value.trim();
        if (!templateName) {
          alert('请输入模板名称');
          return;
        }
        const originalText = createBtn.innerHTML;
        createBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>创建中...';
        createBtn.disabled = true;

        fetch('/assets/label-templates/save/', {
          method: 'POST',
          body: JSON.stringify({
            name: formData.get('name'),
            description: formData.get('description'),
            label_size: formData.get('label_size'),
            labels_per_page: parseInt(formData.get('labels_per_page')),
            include_qr: formData.has('include_qr'),
            include_category: formData.has('include_category'),
            include_department: formData.has('include_department'),
            include_user: formData.has('include_user'),
            is_public: formData.has('is_public'),
            is_default: formData.has('is_default'),
          }),
          headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || getCookie('csrftoken'),
            'X-Requested-With': 'XMLHttpRequest',
          },
        })
          .then((r) => r.json())
          .then((data) => {
            if (data.success) {
              if (window.bootstrap) {
                const modal = window.bootstrap.Modal.getInstance(
                  document.getElementById('createTemplateModal')
                );
                if (modal) modal.hide();
              }
              showAlert('success', '模板创建成功！');
              setTimeout(() => location.reload(), 1000);
            } else {
              showAlert('danger', data.message || '创建失败，请重试');
            }
          })
          .catch(() => showAlert('danger', '网络错误，请重试'))
          .finally(() => {
            createBtn.innerHTML = originalText;
            createBtn.disabled = false;
          });
      });
    }

    // Delete template open modal
    document.querySelectorAll('.delete-template-btn').forEach((btn) => {
      btn.addEventListener('click', function () {
        const templateId = this.dataset.templateId;
        const templateName = this.dataset.templateName;
        const nameEl = document.getElementById('delete-template-name');
        if (nameEl) nameEl.textContent = templateName;
        const confirmBtn = document.getElementById('confirm-delete-template');
        if (confirmBtn) confirmBtn.dataset.templateId = templateId;
        const modalEl = document.getElementById('deleteTemplateModal');
        if (modalEl && window.bootstrap) {
          const modal = new window.bootstrap.Modal(modalEl);
          modal.show();
        }
      });
    });

    // Confirm delete
    const confirmDeleteBtn = document.getElementById('confirm-delete-template');
    if (confirmDeleteBtn) {
      confirmDeleteBtn.addEventListener('click', function () {
        const templateId = this.dataset.templateId;
        const originalText = confirmDeleteBtn.innerHTML;
        confirmDeleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>删除中...';
        confirmDeleteBtn.disabled = true;
        fetch(`/assets/label-templates/${templateId}/delete/`, {
          method: 'POST',
          headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || getCookie('csrftoken'),
            'X-Requested-With': 'XMLHttpRequest',
          },
        })
          .then((r) => r.json())
          .then((data) => {
            if (data.success) {
              if (window.bootstrap) {
                const modal = window.bootstrap.Modal.getInstance(
                  document.getElementById('deleteTemplateModal')
                );
                if (modal) modal.hide();
              }
              showAlert('success', '模板删除成功！');
              setTimeout(() => location.reload(), 1000);
            } else {
              showAlert('danger', data.message || '删除失败，请重试');
            }
          })
          .catch(() => showAlert('danger', '网络错误，请重试'))
          .finally(() => {
            confirmDeleteBtn.innerHTML = originalText;
            confirmDeleteBtn.disabled = false;
          });
      });
    }

    // Create panel preview checkbox updates
    updatePreviewVisibility('create', 'create');
    updatePreviewVisibility('edit', 'preview');

    // Duplicate via delegated click
    document.addEventListener('click', function (e) {
      const btn = e.target.closest('.duplicate-template-btn');
      if (btn) {
        const templateId = btn.dataset.templateId;
        const templateName = btn.dataset.templateName;
        if (confirm(`确定要复制模板 "${templateName}" 吗？`)) {
          duplicateTemplate(templateId);
        }
      }
    });

    // Export function for export buttons that call exportTemplates(range)
    window.exportTemplates = function (range) {
      const url = `/assets/label-templates/export/?format=json&range=${range}&include_preview=false`;
      fetch(url, {
        method: 'GET',
        headers: { 'X-CSRFToken': getCookie('csrftoken') },
      })
        .then((response) => {
          if (response.ok) return response.blob();
          throw new Error('导出失败');
        })
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          a.download = `label_templates_${range}_${new Date().toISOString().split('T')[0]}.json`;
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          showAlert('success', '模板导出成功！');
        })
        .catch(() => showAlert('danger', '导出失败，请重试'));
    };

    // Print mode switch
    document.querySelectorAll('input[name="print_mode"]').forEach((radio) => {
      radio.addEventListener('change', function () {
        const singleAssetInput = document.getElementById('single-asset-input');
        if (!singleAssetInput) return;
        singleAssetInput.style.display = this.value === 'single' ? 'block' : 'none';
      });
    });

    // Confirm use template
    const confirmUseBtn = document.getElementById('confirm-use-template');
    if (confirmUseBtn) {
      confirmUseBtn.addEventListener('click', function () {
        const printMode = document.querySelector('input[name="print_mode"]:checked')?.value;
        if (!printMode || !selectedTemplateId) return;
        if (printMode === 'single') {
          const input = document.getElementById('asset_number');
          const assetNumber = (input && input.value || '').trim();
          if (!assetNumber) {
            alert('请输入资产编号');
            return;
          }
          window.location.href = `/assets/label-print/single/${selectedTemplateId}/?asset_number=${encodeURIComponent(assetNumber)}`;
        } else {
          window.location.href = `/assets/label-print/batch/${selectedTemplateId}/`;
        }
      });
    }
  });
})();
